import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.nio.file.Paths;

public class WriteToCacheAndWait {

    public static void main(String[] args) throws IOException, InterruptedException {
        // 创建文件路径
        Path path = Paths.get("write_to_cache_later.dat");

        // 打开文件并准备写操作
        FileChannel fileChannel = FileChannel.open(path, StandardOpenOption.CREATE, StandardOpenOption.WRITE);
        String data = "This data is written to cache, but not yet flushed to disk.";
        byte[] dataBytes = data.getBytes();

        // 将数据写入 ByteBuffer
        ByteBuffer buffer = ByteBuffer.wrap(dataBytes);

        // 顺序写入文件，但不调用 force()，数据不会立即刷写到磁盘
        while (buffer.hasRemaining()) {
            fileChannel.write(buffer);
            Thread.sleep(1000);
        }

        // 数据写入缓存，但没有立即刷新到磁盘
        System.out.println("Data written to cache, but not yet flushed to disk.");

        // 程序等待 10 秒，模拟操作系统将数据从内存缓存刷写到磁盘
        System.out.println("Waiting for 10 seconds before checking if the data is flushed to disk...");

        // 在这期间数据不会马上落盘，因为文件仍未关闭
        Thread.sleep(10000); // 延迟 10 秒

        // 在此等待 10 秒后，尝试查看文件。此时文件可能仍未刷新到磁盘。
        System.out.println("Now you can check the file content. It should still be in cache, not yet flushed to disk.");

        // 关闭文件通道，操作系统将会在关闭时写入缓存到磁盘
        fileChannel.close();  // 在关闭时操作系统会强制将缓存刷写到磁盘
    }
}
